package net.youyi.crazycopyer.ui;

import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Rect;
import android.media.Image;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;

import net.youyi.crazycopyer.R;
import net.youyi.crazycopyer.entity.ImageFile;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by xzp on 16/4/11.
 */
public class SelectPhotoActivity extends BaseActivity{
    private RecyclerView mRecycler;
    private GridLayoutManager mLayoutManager;
    private PhotoAdapter mAdapter;
    private PhotoTask mTask;
    private boolean mIsLast;
    private int mPerPageNum=40;
    private int mItemOffset;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_select_photo);
        mRecycler= (RecyclerView) this.findViewById(R.id.photo_list);
        mLayoutManager=new GridLayoutManager(this,3);
        mRecycler.setLayoutManager(mLayoutManager);
        mTask=new PhotoTask();
        mAdapter=new PhotoAdapter();
        mRecycler.setAdapter(mAdapter);
        mRecycler.addOnScrollListener(mScrollListener);
        mItemOffset= (int) (getResources().getDisplayMetrics().density*2);
        mRecycler.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
                outRect.set(mItemOffset,mItemOffset,mItemOffset,mItemOffset);
            }
        });
        mTask.execute();
    }
    private RecyclerView.OnScrollListener mScrollListener=new RecyclerView.OnScrollListener() {
        @Override
        public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
           if(!mIsLast && newState==RecyclerView.SCROLL_STATE_IDLE){
               if(mLayoutManager.findLastVisibleItemPosition()>=mAdapter.getItemCount()-1){
                   if(mTask==null || mTask.getStatus() == AsyncTask.Status.FINISHED){
                       mTask=new PhotoTask();
                       if(mAdapter.getItemCount()>0)
                           mTask.execute(mAdapter.getList().get(mAdapter.getItemCount()-1).getId());
                       else
                           mTask.execute();
                   }
               }
           }
        }
    };
    private class PhotoAdapter extends RecyclerView.Adapter<PhotoAdapter.PhotoHolder>{
        private List<ImageFile> mList;

        public PhotoAdapter() {
            mList=new ArrayList<ImageFile>();
        }
        public List<ImageFile> getList(){
            return mList;
        }
        @Override
        public PhotoHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view=getLayoutInflater().inflate(R.layout.photo_item,parent,false);
            return new PhotoHolder(view);
        }

        @Override
        public void onBindViewHolder(PhotoHolder holder, int position) {
            ImageFile imageFile=getList().get(position);
            Glide.with(SelectPhotoActivity.this).load(new File(imageFile.getData())).centerCrop().diskCacheStrategy(DiskCacheStrategy.NONE)
                    .dontAnimate().into(holder.photoImage);
        }

        @Override
        public int getItemCount() {
            return mList.size();
        }
        class PhotoHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
            ImageView photoImage;
            public PhotoHolder(View itemView) {
                super(itemView);
                itemView.setOnClickListener(this);
                photoImage= (ImageView) itemView.findViewById(R.id.photo_image);
            }

            @Override
            public void onClick(View view) {
                int position=getAdapterPosition();
                if(position!=RecyclerView.NO_POSITION){
                    Intent intent=new Intent();
                    intent.putExtra("path",getList().get(position).getData());
                    setResult(RESULT_OK,intent);
                    finish();
                }
            }
        }
    }
    private class PhotoTask extends AsyncTask<String,Void,List<ImageFile>>{
        @Override
        protected List<ImageFile> doInBackground(String... ids) {
            ContentResolver resolver = getContentResolver();
            StringBuffer buffer=new StringBuffer();
            if(ids.length>0) {
                buffer.append(MediaStore.Images.ImageColumns._ID+" < "+ids[0]);
                buffer.append(" and ");
            }
            buffer.append("("+MediaStore.Images.Media.MIME_TYPE+" = ? or "+MediaStore.Images.Media.MIME_TYPE+" = ?)");
//            buffer.append(" and ");
            Log.e("Photo_Sql",buffer.toString());
            Cursor cursor = resolver.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, null,buffer.toString(), new String[]{"image/jpeg","image/png"},
                    MediaStore.Images.ImageColumns._ID+" desc limit "+mPerPageNum);
            List<ImageFile> fileList=new ArrayList<ImageFile>(mPerPageNum);
            while (cursor.moveToNext()) {
                String data = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
                String id=cursor.getString(cursor.getColumnIndex(MediaStore.Images.ImageColumns._ID));
                ImageFile file=new ImageFile(id,data);
                fileList.add(file);
            }
            return fileList;
        }

        @Override
        protected void onPostExecute(List<ImageFile> imageFiles) {
            super.onPostExecute(imageFiles);
            int count=mAdapter.getItemCount();
            if(imageFiles.size()<mPerPageNum)
                mIsLast=true;
            mAdapter.getList().addAll(imageFiles);
            mAdapter.notifyItemRangeInserted(count,imageFiles.size());
        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(mTask!=null && mTask.getStatus()!= AsyncTask.Status.FINISHED){
            mTask.cancel(true);
        }
    }
}
